<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" @click="handleCreate" type="primary" icon="el-icon-plus">新增菜单</el-button>
    </div>

    <tree-table :data="data" :columns="columns" border>
      <slot>
        <el-table-column label="类型" width="80">
          <template slot-scope="ascope">
            <el-tag v-if="ascope.row.type==='ROOT'" type="success">{{ascope.row.type | typeFilter}}</el-tag>
            <el-tag v-else-if="ascope.row.type==='MENU'">{{ascope.row.type | typeFilter}}</el-tag>
            <el-tag v-else type="warning">{{ascope.row.type | typeFilter}}</el-tag>
          </template>
        </el-table-column>
      </slot>
      <slot>
        <el-table-column label="操作" width="250">
          <template slot-scope="ascope">
            <el-button type="success" size="mini" @click="handleChildCreate(ascope.row)" v-if="ascope.row.type!=='BUTTON'">新增</el-button>
            <el-button type="primary" size="mini" @click="handleUpdate(ascope.row)">修改</el-button>
            <el-button type="danger" size="mini" @click="handleDelete(ascope.row)">删除</el-button>
          </template>
        </el-table-column>
      </slot>
    </tree-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name"></el-input>
        </el-form-item>

        <el-form-item v-if="this.temp.type!=='BUTTON'" label="前端路由" prop="routerPath">
          <el-input v-model="temp.routerPath"></el-input>
        </el-form-item>
        <el-form-item label="路由名称" prop="routerName">
          <el-input v-model="temp.routerName"></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="temp.remark"></el-input>
        </el-form-item>
        <!-- <el-form-item v-if="this.temp.type!=='BUTTON'" label="排序" prop="sort">
          <el-input v-model.number="temp.sort"></el-input>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="dialogStatus !== 'info'">
        <el-button @click="dialogFormVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button v-if="dialogStatus=='create'||dialogStatus=='createChild'" type="primary" @click="createData">{{$t('table.confirm')}}</el-button>
        <el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

    <!-- <el-dialog title="菜单操作" :visible.sync="sysMenuOpdialogVisible">
      <el-table :key="sysMenuOpList.ID" :data="sysMenuOpList" border fit highlight-current-row style="width: 100%">
        <el-table-column align="center" :label="$t('table.id')" width="65">
          <template slot-scope="scope">
            <span>{{scope.$index+1}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="名称">
          <template slot-scope="scope">
            <template v-if="scope.row.edit">
              <el-form :model="scope.row" ref="nameForm" >
                <el-form-item prop="name" :rules="[{ required: true, message: '名称不能为空', trigger: 'blur' }]">
                  <el-input class="edit-input" size="small" v-model="scope.row.name"></el-input>
                </el-form-item>
              </el-form>
            </template>
            <span v-else>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="编码">
          <template slot-scope="scope">
            <template v-if="scope.row.edit">
              <el-form :model="scope.row" ref="codeForm">
                <el-form-item prop="code" :rules="[{ required: true, message: '编码不能为空', trigger: 'blur' }]">
                  <el-input class="edit-input" size="small" v-model="scope.row.code"></el-input>
                </el-form-item>
              </el-form>
            </template>
            <span v-else>{{ scope.row.code }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="权限编码">
          <template slot-scope="scope">
            <span>{{scope.authCode}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('table.actions')" width="360" class-name="small-padding fixed-width">
          <template slot-scope="scope">
              <el-button type="warning" size="mini" v-if="!scope.row.id" @click="saveMenuOp(scope)">保存</el-button>
              <el-button type="warning" size="mini" v-if="scope.row.edit&&scope.row.id" @click="updateMenuOp(scope.row)">修改</el-button>
              <el-button size="mini" type="danger" v-if="scope.row.edit&&scope.row.id" @click="handleCancelMenuOpEdit(scope.row)">取消</el-button>
              <el-button size="mini" type="danger" v-if="scope.row.edit&&!scope.row.id" @click="handleCancelMenuOpAdd(scope.row)">取消</el-button>
              <el-button type="primary" size="mini" v-if="!scope.row.edit&&dialogStatus!=='createSysMenuOp'" @click="handleMenuOpEdit(scope.row)">{{$t('table.edit')}}</el-button>
              <el-button size="mini" type="danger" v-if="!scope.row.edit&&dialogStatus!=='createSysMenuOp'" @click="deleteMenuOp(scope.row,'deleted')">{{$t('table.delete')}}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button v-if="dialogStatus!=='createSysMenuOp'" @click="sysMenuOpdialogVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button v-if="dialogStatus!=='createSysMenuOp'&&dialogStatus!=='editSysMenuOp'" type="success" @click="createMenuOpData()">新增</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>
<script>
import treeTable from '@/components/TreeTable'
import {
  fetchList,
  createSysMenu,
  deleteSysMenu,
  infoSysMenu,
  updateSysMenu
} from '@/api/user/sysMenu'

export default {
  name: 'treeTableDemo',
  components: { treeTable },
  data() {
    const validateRouterUri = (rule, value, callback) => {
      const urlregex = /\/[a-zA-z]*$/

      if (value) {
        if (urlregex.test(value)) {
          callback()
        } else {
          callback('url格式填写不正确(/aa/bb)')
        }
      } else {
        callback()
      }
    }
    return {
      tableKey: 0,
      dialogFormVisible: false,
      sysMenuOpdialogVisible: false,
      sysMenuOpList: [],
      menuId: undefined,
      dialogStatus: '',
      columns: [
        {
          text: '名称',
          value: 'name',
          width: 200
        },
        {
          text: '路由地址',
          value: 'routerPath'
        },
        {
          text: '路由名称',
          value: 'routerName',
          width: 300
        },
        {
          text: '备注',
          value: 'remark'
        }
      ],
      data: [],
      temp: {
        name: '',
        code: '',
        remark: '',
        routerPath: '',
        routerName: '',
        parentId: '',
        level: '',
        sort: undefined
      },
      textMap: {
        update: '修改',
        create: '新增',
        info: '详情',
        createChild: '新增'
      },
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        code: [{ required: true, message: '编码不能为空', trigger: 'blur' }],
        remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
        routerPath: [
          { required: true, message: '前端路由不能为空', trigger: 'blur' },
          { validator: validateRouterUri, trigger: 'blur' }
        ],
        routerName: [
          { required: true, message: '路由名称不能为空', trigger: 'blur' }
        ],
        parentId: [
          { required: true, message: '父ID不能为空', trigger: 'blur' }
        ],
        level: [{ required: true, message: '层级不能为空', trigger: 'blur' }]
        // sort: [
        //   { required: true, message: '层级不能为空' },
        //   { type: 'number', message: '排序只能是数字' }
        // ]
      }
    }
  },
  filters: {
    typeFilter(type) {
      const statusMap = {
        ROOT: '目录',
        MENU: '菜单',
        BUTTON: '按钮'
      }
      return statusMap[type]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      var param = { parentId: '0' }
      fetchList(param).then(response => {
        this.data = response.content
      })
    },
    resetTemp() {
      this.temp = {
        name: '',
        code: '',
        remark: '',
        routerPath: '',
        routerName: '',
        parentId: '',
        level: '',
        sort: undefined
      }
    },
    // 打开一级菜单新增dialog
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.temp.parentId = '0'
      this.temp.level = 0
      this.temp.type = 'ROOT'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 子菜单新增dialog
    handleChildCreate(row) {
      this.resetTemp()
      this.dialogStatus = 'createChild'
      this.dialogFormVisible = true
      this.temp.parentId = row.id
      this.temp.level = row.level + 1
      if (row.type === 'ROOT') {
        this.temp.type = 'MENU'
      } else if (row.type === 'MENU') {
        this.temp.type = 'BUTTON'
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 保存
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createSysMenu(this.temp).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 删除操作
    handleDelete(row) {
      this.$confirm('此操作将永久删除该菜单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 调用删除接口
          var p = { id: row.id }
          deleteSysMenu(p).then(response => {
            if (response.success) {
              this.getList()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 更新页面
    handleUpdate(row) {
      infoSysMenu(row.id).then(response => {
        this.resetTemp()
        this.temp = Object.assign({}, response.content) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateSysMenu(tempData).then(response => {
            if (response.success) {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    // handleButtonCreate(row) {
    //   infoSysMenuOpList(row.id).then(response => {
    //     this.dialogStatus = 'infoSysMenuOp'
    //     var rArray = []
    //     if (response.content.length > 0) {
    //       var editObj = { edit: false }
    //       response.content.forEach(function(c) {
    //         var dd = Object.assign(c, editObj)
    //         rArray.push(dd)
    //       })
    //     }
    //     this.sysMenuOpList = rArray
    //     this.sysMenuOpdialogVisible = true
    //     this.menuId = row.id
    //   })
    // },
    createMenuOpData(menuOpScope) {
      this.dialogStatus = 'createSysMenuOp'
      var menuOp = {
        id: undefined,
        name: '',
        code: '',
        menuId: '',
        remark: '',
        authCode: '',
        edit: true
      }
      this.sysMenuOpList.push(menuOp)
    },
    // 取消菜单操作新增列
    handleCancelMenuOpAdd(row) {
      this.sysMenuOpList.splice(-1, 1)
      this.dialogStatus = 'infoSysMenuOp'
    },
    // 取消菜单操作修改
    handleCancelMenuOpEdit(row) {
      row.edit = false
      this.dialogStatus = 'infoSysMenuOp'
    },
    // saveMenuOp(scope) {
    //   this.$refs['nameForm'].validate(valid => {
    //     if (valid) {
    //       this.$refs['codeForm'].validate(valid => {
    //         if (valid) {
    //           scope.row.menuId = this.menuId
    //           createSysMenuOp(scope.row).then(response => {
    //             if (response.success) {
    //               scope.row.id = response.content.id
    //               scope.row.edit = false
    //               this.dialogStatus = 'infoSysMenuOp'
    //               this.$notify({
    //                 title: '成功',
    //                 message: '创建成功',
    //                 type: 'success',
    //                 duration: 2000
    //               })
    //             }
    //           })
    //         }
    //       })
    //     }
    //   })
    // },
    handleMenuOpEdit(row) {
      row.edit = true
      this.dialogStatus = 'editSysMenuOp'
    },
    // updateMenuOp(row) {
    //   this.$refs['nameForm'].validate(valid => {
    //     if (valid) {
    //       this.$refs['codeForm'].validate(valid => {
    //         if (valid) {
    //           updateSysMenuOp(row).then(response => {
    //             if (response.success) {
    //               row.edit = false
    //               this.dialogStatus = 'infoSysMenuOp'
    //               this.$notify({
    //                 title: '成功',
    //                 message: '修改成功',
    //                 type: 'success',
    //                 duration: 2000
    //               })
    //             }
    //           })
    //         }
    //       })
    //     }
    //   })
    // },
    //   deleteMenuOp(row) {
    //     this.$confirm('此操作将永久删除该菜单按钮, 是否继续?', '提示', {
    //       confirmButtonText: '确定',
    //       cancelButtonText: '取消',
    //       type: 'warning'
    //     }).then(() => {
    //       // 调用删除接口
    //       var p = { id: row.id }
    //       deleteSysMenuOp(p).then(response => {
    //         if (response.success) {
    //           infoSysMenuOpList(this.menuId).then(response => {
    //             var rArray = []
    //             if (response.content.length > 0) {
    //               var editObj = { edit: false }
    //               response.content.forEach(function(c) {
    //                 var dd = Object.assign(c, editObj)
    //                 rArray.push(dd)
    //               })
    //             }
    //             this.sysMenuOpList = rArray
    //           })
    //           this.$message({
    //             type: 'success',
    //             message: '删除成功!'
    //           })
    //         }
    //       })
    //     }).catch(() => {
    //       this.$message({
    //         type: 'info',
    //         message: '已取消删除'
    //       })
    //     })
    //   }
    // },
    restQuery() {
      this.listQuery.expireStatus = ''
      this.listQuery.balanceType = ''
      this.listQuery.contractStatus = ''
      this.listQuery.compoundSearch = ''
      this.getList()
    }
  }
}
</script>
